function stringify(o){
	return Prism.highlight(JSON.stringify(o).replace('{','').replace('}','').replace(/,/g,'\n'), Prism.languages.properties);
}

var formatTime = function(date) {
	return moment(parseInt(date)).format('YYYY-MM-DD hh:mm:ss');
};

var formatSize = function(size) {
	if(size>1024*1024*1024){
		return (size/1024/1024/1024).toFixed(2) + "GB";
	}
	
	if(size>1024*1024){
		return (size/1024/1024).toFixed(2) + "MB";
	}
	
	if(size>1024){
		return (size/1024).toFixed(2) + "KB";
	}
	
	return size + "B";
};

$.params = (function(){
   var url = location.search;
   var params = {};
   if (url.indexOf("?") != -1) {
      var str = url.substr(1);
      strs = str.split("&");
      for(var i = 0; i < strs.length; i ++) {
    	  params[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
      }
   }
   return params;
})();

$.fn.serializeObject = function() {  
    var o = {};  
    var a = this.serializeArray();  
    $.each(a, function() {  
        if (o[this.name]) {  
            if (!o[this.name].push) {  
                o[this.name] = [ o[this.name] ];  
            }  
            o[this.name].push(this.value || '');  
        } else {  
            o[this.name] = this.value || '';  
        }  
    });  
    return o;  
};  

$.fn.fill = function(data){
return this.each(function(){
    var input, name;
    if(data == null){this.reset(); return; }
    for(var i = 0; i < this.length; i++){  
        input = this.elements[i];
        // checkbox的name可能是name[]数组形式
        name = (input.type == "checkbox")? input.name.replace(/(.+)\[\]$/, "$1") : input.name;
        if(data[name] == undefined) continue;
        switch(input.type){
            case "checkbox":
                if(data[name] == ""){
                    input.checked = false;
                }else{
                    // 数组查找元素
                    if(data[name].indexOf(input.value) > -1){
                        input.checked = true;
                    }else{
                        input.checked = false;
                    }
                }
            break;
            case "radio":
                if(data[name] == ""){
                    input.checked = false;
                }else if(input.value == data[name]){
                    input.checked = true;
                }
            break;
            case "button": break;
            default: input.value = data[name];
        }
    }
});
};

$.extend( $.fn.dataTable.defaults, {
	"lengthMenu": [[3, 25, 50, -1], [3, 25, 50, "All"]],
	"pagingType": "full_numbers",
	"searching": false,
	"serverSide":true,
	"ordering": false,
	"autoWidth": false,
	"dom": '<"datatable-scroll"t><"datatable-footer length-left"ip>',
	"language": {
	    "sProcessing":   "处理中...",
	    "sLengthMenu":   "每页 _MENU_ 项，",
	    "sZeroRecords":  "没有匹配结果",
	    "sInfo":         "当前显示第 _START_ 至 _END_ 项，共 _TOTAL_ 项。",
	    "sInfoEmpty":    "当前显示第 0 至 0 项，共 0 项",
	    "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
	    "sInfoPostFix":  "",
	    "sSearch":       "搜索:",
	    "sUrl":          "",
	    "sEmptyTable":     "表中数据为空",
	    "sLoadingRecords": "载入中...",
	    "sInfoThousands":  ",",
	    "oPaginate": {
	        "sFirst":    "首页",
	        "sPrevious": "上页",
	        "sNext":     "下页",
	        "sLast":     "末页",
	        "sJump":     "跳转"
	    },
	    "oAria": {
	        "sSortAscending":  ": 以升序排列此列",
	        "sSortDescending": ": 以降序排列此列"
	    },
/*	    "select": {
	        rows: {
	            _: "选中 %d 行",
	            1: "选中 1 行"
	        }
	    }*/
	}
});

$.validator.addMethod("chrnum", function(value, element) {
	var chrnum = /^([a-zA-Z0-9]+)$/;
	return this.optional(element) || (chrnum.test(value));
}, "只能输入数字和字母(字符A-Z, a-z, 0-9)");


// Initialize
$.validator.setDefaults({
    ignore: 'input[type=hidden], .select2-search__field', // ignore hidden fields
    errorClass: 'validation-error-label',
    successClass: 'validation-valid-label',
    highlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
    },
    unhighlight: function(element, errorClass) {
        $(element).removeClass(errorClass);
    },

    // Different components require proper error label placement
    errorPlacement: function(error, element) {

        // Styled checkboxes, radios, bootstrap switch
        if (element.parents('div').hasClass("checker") || element.parents('div').hasClass("choice") || element.parent().hasClass('bootstrap-switch-container') ) {
            if(element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
                error.appendTo( element.parent().parent().parent().parent() );
            }
             else {
                error.appendTo( element.parent().parent().parent().parent().parent() );
            }
        }

        // Unstyled checkboxes, radios
        else if (element.parents('div').hasClass('checkbox') || element.parents('div').hasClass('radio')) {
            error.appendTo( element.parent().parent().parent() );
        }

        // Input with icons and Select2
        else if (element.parents('div').hasClass('has-feedback') || element.hasClass('select2-hidden-accessible')) {
            error.appendTo( element.parent() );
        }

        // Inline checkboxes, radios
        else if (element.parents('label').hasClass('checkbox-inline') || element.parents('label').hasClass('radio-inline')) {
            error.appendTo( element.parent().parent() );
        }

        // Input group, styled file input
        else if (element.parent().hasClass('uploader') || element.parents().hasClass('input-group')) {
            error.appendTo( element.parent().parent() );
        }

        else {
            error.insertAfter(element);
        }
    },
    validClass: "validation-valid-label",
    success: function(label) {
        //label.addClass("validation-valid-label").text("Success.")
    	label.remove();
    }
});

jQuery.extend(jQuery.validator.messages, {  
    required: "必填字段",  
	remote: "请修正该字段",  
	email: "请输入正确格式的电子邮件",  
	url: "请输入合法的网址",  
	date: "请输入合法的日期",  
	dateISO: "请输入合法的日期 (ISO).",  
	number: "请输入合法的数字",  
	digits: "只能输入整数",  
	creditcard: "请输入合法的信用卡号",  
	equalTo: "请再次输入相同的值",  
	accept: "请输入拥有合法后缀名的字符串",  
	maxlength: jQuery.validator.format("请输入长度最多是 {0} 的值"),  
	minlength: jQuery.validator.format("请输入长度最少是 {0} 的值"),  
	rangelength: jQuery.validator.format("请输入长度介于 {0} 和 {1} 之间的值"),  
	range: jQuery.validator.format("请输入一个介于 {0} 和 {1} 之间的值"),  
	max: jQuery.validator.format("请输入一个最大为 {0} 的值"),  
	min: jQuery.validator.format("请输入一个最小为 {0} 的值")  
});  

$.block = function(){
	$.blockUI({ 
	    message: '<i class="icon-spinner4 spinner"></i>',
	    overlayCSS: {
	        backgroundColor: '#1b2024',
	        opacity: 0.8,
	        cursor: 'wait'
	    },
	    css: {
	        border: 0,
	        color: '#fff',
	        padding: 0,
	        backgroundColor: 'transparent'
	    }
	});
}


$(document).ajaxStart($.block)
	.ajaxComplete(function(){$.unblockUI();})
	.ajaxError(function(jqXHR, textStatus, errorMsg){
		var msg = textStatus.responseJSON ? textStatus.responseJSON.message : "未知错误";
		swal("请求失败", msg, "error");        
	});


$(function(){
	if(window.juicer){
		juicer.register('formatTime', formatTime);
		juicer.register('stringify', stringify);
		juicer.register('formatSize', formatSize);
	}
	
	$("#editpwd_form").validate();
	
	$("#editpwd").click(function(){
		$("#editpwd_form").validate().resetForm();
		$("#editpwd_form")[0].reset();
	});
	
	$("#submitEditPwd").click(function(){
		if($("#editpwd_form").valid()){
			$('.close').click();
			$.post(contextpath+"user/modifyPwd", $("#editpwd_form").serialize(), function(){
				swal("","修改成功","success");
			});	
		}
	});

    String.prototype.setTokens = function (replacePairs) {
        var str = this.toString(), key, re;
        for (key in replacePairs) {
            if (replacePairs.hasOwnProperty(key)) {
                re = new RegExp("\{" + key + "\}", "g");
                str = str.replace(re, replacePairs[key]);
            }
        }
        return str;
    };
})